package top.maof.book.controller;

import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import top.maof.book.model.Contents;
import top.maof.book.model.History;
import top.maof.book.model.Role;
import top.maof.book.result.ApiResponse;
import top.maof.book.result.PageData;
import top.maof.book.result.PageWrap;
import top.maof.book.result.Result;
import top.maof.book.service.ContentsService;
import top.maof.book.service.HistoryService;
import top.maof.book.service.WebService;
import top.maof.book.spider.runtime.Pair;
import top.maof.book.utils.JWTUtils;
import top.maof.book.vo.ContentsVo;
import top.maof.book.vo.service.ContentsVoService;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * Created by CodeX4J.
 */
@Controller
@RequestMapping("/contents")
@ResponseBody
public class ContentsController {
    @Autowired
    private ContentsService contentsService;

    @Autowired
    private ContentsVoService contentsVoService;

    @Autowired
    WebService webService;

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("新建")
    @PostMapping("/create")
    public ApiResponse create(@RequestBody Contents contents) {
        return ApiResponse.success(contentsService.save(contents));
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("根据ID删除")
    @GetMapping("/delete/{id}")
    public ApiResponse deleteById(@PathVariable Integer id) {
        contentsService.removeById(id);
        return ApiResponse.success(null);
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("批量删除")
    @GetMapping("/delete/batch")
    public ApiResponse deleteByIdInBatch(@RequestParam String ids) {
        String[] idArray = ids.split(",");
        List<Integer> idList = new ArrayList<>();
        for (String id : idArray) {
            idList.add(Integer.valueOf(id));
        }
        contentsService.removeBatchByIds(idList);
        return ApiResponse.success(null);
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("根据ID修改")
    @PostMapping("/updateById")
    public ApiResponse updateById(@RequestBody Contents contents) {
        contentsService.updateById(contents);
        return ApiResponse.success(null);
    }

    @ApiOperation("分页查询")
    @PostMapping("/page")
    public ApiResponse<PageData<Contents>> findPage(@RequestBody PageWrap<Contents> pageWrap) {
        return ApiResponse.success(contentsService.findPage(pageWrap));
    }

    @PostMapping("")
    @RequiresRoles(value = {Role.ADMIN})
    public Result add(Contents contents) throws Exception {
        if (contentsService.add(contents) > 0) return Result.success();
        return Result.response_400();
    }

    @GetMapping("/{id}")
    public Result find(@PathVariable("id") int id) throws Exception {
        Contents contents = contentsService.find(id);
        if (contents != null) return Result.success(contents);
        return Result.response_404();
    }

    @PutMapping("")
    @RequiresRoles(value = {Role.ADMIN})
    public Result update(Contents contents) throws Exception {
        if (contentsService.update(contents) > 0) return Result.success();
        return Result.response_400();
    }

    @DeleteMapping("/{id}")
    @RequiresRoles(value = {Role.ADMIN})
    public Result delete(@PathVariable("id") int id) throws Exception {
        if (contentsService.delete(id) > 0) return Result.success();
        return Result.response_400();
    }

    @Autowired
    HistoryService historyService;

    @GetMapping("/vo/{bookId}")
    @ApiOperation("获取书所有站点的资源")
    public Result<ContentsVo> vo(@PathVariable("bookId") Integer bookId, @RequestHeader(value = "token", required = false) String token,
                                 HttpServletRequest request) throws Exception {
        // 插入历史代码
//        History history = new History();
//        history.setBookId(bookId);
//        history.setUserId(null);
//        if (JWTUtils.checkToken(token)) {
//            Integer userId = JWTUtils.getUserId(token);
//            history.setUserId(userId);
//        }
//        String remoteAddr = request.getRemoteAddr();
//        history.setIp(remoteAddr);
//        history.setInsertDate(new Date());
//        historyService.add(history);

        ContentsVo contentsVo = contentsVoService.contentsVo(bookId);
        if (contentsVo != null) return Result.success(contentsVo);
        return Result.response_404();
    }

    @ApiOperation("获取书指定网站的资源")
    @GetMapping("/vo/{bookId}/{webId}")
    public Result<Set<Pair>> vo(@PathVariable("bookId") Integer bookId, @PathVariable("webId") Integer webId)
            throws Exception {

        Set<Pair> set = contentsVoService.contentsSet(bookId, webId);
        if (set != null && set.size() > 0)
            return Result.success(set);
        return Result.response_404();
    }
}
